import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, setToken } from '@/utils/auth'




axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
// create an axios instance
console.log(process.env.VUE_APP_BASE_API)
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API ? '/api' : '/',
  // baseURL:'http://eportal.hesw.tax.cn/syfxht', 
  // baseURL:'http://eportal.hesw.tax.cn/sqzltj', 
  // baseURL:'http://127.0.0.1:8080', 
  baseURL: 'http://192.168.1.104:30279',
  // baseURL:'http://172.16.0.3:8080', 
  // 超时
  timeout: 1800000,
})

// request interceptor
service.interceptors.request.use(
  config => {
    console.log(config)
    // do something before request is sent
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false;
    /* eslint-disable-next-line */
    if (getToken() && !isToken) {
      config.headers['Authorization'] = getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
    }

    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {

    // 相应头部包含 content-disposition 可能是要下载的文件名在其中
    if (response.headers && Object.keys(response.headers).includes('content-disposition')) {
      if (response.headers['content-disposition'].indexOf('filename=') != -1) {
        let arr = response.headers['content-disposition'].split('filename=');
        localStorage.setItem('jmFileName', arr.length == 2 ? decodeURIComponent(arr[1]) : '未知文件.txt');
      }
    }
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code) {
      if (res.code == 500) {
        Message({
          message: res.message,
          type: 'error'
        });
        if(res.message =='登录过期'){
          localStorage.clear();
        }
        return Promise.reject(new Error(msg));
      }else  if (res.code != 200) {
        Message({
          message: res.message || 'Error',
          type: 'error',
          duration: 5 * 1000
        })

        // 50008: Illegal token; 50012: Other clienpmnts logged in; 50014: Token expired;
        if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
          // to re-login
          MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
            confirmButtonText: 'Re-Login',
            cancelButtonText: 'Cancel',
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          })
        }
        return Promise.reject(res);
      } else {
        setToken(res.token)
        return res
      }
    } else {
      return res
    }

  },
  error => {
    //请求结束关闭loading
    // loadCounter.hide();
    let { message } = error;
    console.log(message)
    if (message == '登录过期') {

    }
    if (message === 'Network Error') {
      message = '后端接口连接异常';
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时';
    } else if (message.includes('Request failed with status code')) {

      message = '系统接口' + message.substr(message.length - 3) + '异常' + '请重新登录';

    }
    Message({
      message: message,
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
)

export default service
